package cn.leida.ruoyi.framework.jpa.tools;

import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lei
 * @create 2024-11-04 11:56
 */
public class SpringControllerUtil {
    public static List<String> baseMethodUrls(Class<?> clazz) {
        List<String> urls = new ArrayList<>();
        List<String> methodUrls = methodUrls(clazz);
        String baseUrl = baseUrl(clazz);
        for (String methodUrl : methodUrls) {
            urls.add(baseUrl + methodUrl);
        }
        return urls;
    }

    public static String baseUrl(Class<?> clazz) {
        RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
        String baseUrl = "";
        if (requestMapping != null) {
            baseUrl = firstValue(requestMapping.value());
        }
        return baseUrl;
    }

    public static String baseName(Class<?> clazz) {
        RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
        String baseUrl = "";
        if (requestMapping != null) {
            baseUrl = requestMapping.name();
        }
        return baseUrl;
    }

    public static List<String> methodUrls(Class<?> clazz) {
        List<String> methodUrls = new ArrayList<>();
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            GetMapping get = method.getAnnotation(GetMapping.class);
            if (get != null) {
                String methodUrl = firstValue(get.value());
                methodUrls.add(methodUrl);
            }
        }
        return methodUrls;
    }

    public static String firstValue(String[] values) {
        if (values != null) {
            for (String url : values) {
                if (StrUtil.isNotBlank(url)) {
                    return url;
                }
            }
        }
        return "";
    }
}
